<template>
  <v-app>
    <!-- 顶部导航栏 -->
    <v-app-bar color="primary" dark>
      <v-app-bar-title class="d-flex align-center">
        <v-img src="../ico/logo.png" alt="Logo" width="32" height="32" class="mr-3 logo-img"></v-img>
        <v-icon start>mdi-office-building</v-icon>
        会议室预约系统
      </v-app-bar-title>

      <v-spacer></v-spacer>

      <v-btn v-for="item in menuItems" :key="item.title" :to="item.path" text class="mx-2">
        <v-icon start>{{ item.icon }}</v-icon>
        {{ item.title }}
      </v-btn>

      <v-btn @click="checkLoginStatus" text class="mx-2">
        <v-icon start>mdi-account-check</v-icon>
        验证登录
      </v-btn>

      <v-btn @click="showUserInfo = true" text class="mx-2">
        <v-icon start>mdi-account-circle</v-icon>
        个人信息
      </v-btn>

      <v-btn @click="logout" text>
        <v-icon start>mdi-logout</v-icon>
        退出
      </v-btn>

      <v-btn color="secondary" @click="$router.push('/admin/login')" class="ml-2">
        <v-icon start>mdi-account-key</v-icon>管理员登录
      </v-btn>
    </v-app-bar>

    <!-- 主要内容区域 -->
    <v-main>
      <v-container fluid>
        <!-- 欢迎卡片 -->
        <v-row>
          <v-col cols="12">
            <v-btn color="primary" @click="$router.push('/')" class="mb-4">
              <v-icon start>mdi-home</v-icon>返回主页
            </v-btn>
          </v-col>
        </v-row>

        <v-row>
          <v-col cols="12">
            <v-card class="mb-6">
              <v-card-title class="text-h4 text-center">
                欢迎使用会议室预约系统
              </v-card-title>
              <v-card-text class="text-center text-body-1">
                高效管理您的会议室预约，提升工作效率
              </v-card-text>
            </v-card>
          </v-col>
        </v-row>

        <!-- 功能卡片 -->
        <v-row>
          <v-col v-for="card in featureCards" :key="card.title" cols="12" md="4">
            <v-card :to="card.path" hover class="h-100 d-flex flex-column">
              <v-card-title class="text-h6">
                <v-icon start :color="card.color">{{ card.icon }}</v-icon>
                {{ card.title }}
              </v-card-title>
              <v-card-text class="flex-grow-1">
                {{ card.description }}
              </v-card-text>
              <v-card-actions>
                <v-btn :color="card.color" variant="outlined" block>
                  立即使用
                </v-btn>
              </v-card-actions>
            </v-card>
          </v-col>
        </v-row>

        <!-- 快速预约 -->
        <v-row class="mt-6">
          <v-col cols="12">
            <v-card>
              <v-card-title class="text-h5 d-flex justify-space-between align-center">
                <span>
                  <v-icon start color="primary">mdi-clock-fast</v-icon>
                  快速预约
                </span>
                <v-btn icon @click.stop="refreshQuickBooking">
                  <v-icon>mdi-refresh</v-icon>
                </v-btn>
              </v-card-title>
              <v-card-text @click.stop="refreshQuickBooking">
                <v-row>
                  <v-col cols="12" md="3">
                    <v-select v-model="quickBooking.roomId" :items="availableRooms" item-title="name" item-value="id"
                      label="选择会议室"></v-select>
                  </v-col>
                  <v-col cols="12" md="3">
                    <v-text-field v-model="quickBooking.date" label="日期" type="date"></v-text-field>
                  </v-col>
                  <v-col cols="12" md="2">
                    <v-select v-model="quickBooking.startHour" :items="timeSlots" label="开始时间"></v-select>
                  </v-col>
                  <v-col cols="12" md="2">
                    <v-select v-model="quickBooking.endHour" :items="timeSlots" label="结束时间"></v-select>
                  </v-col>
                  <v-col cols="12" md="2">
                    <v-text-field v-model="quickBooking.topic" label="会议主题" :rules="[v => !!v || '会议主题必填']"
                      maxlength="50" counter></v-text-field>
                  </v-col>
                  <v-col cols="12" md="2" class="d-flex align-center">
                    <v-btn color="primary" @click="quickBook" :loading="quickBooking.loading" block>
                      快速预约
                    </v-btn>
                  </v-col>
                </v-row>
              </v-card-text>
            </v-card>
          </v-col>
        </v-row>

        <!-- 参会体验卡片 -->
        <v-row class="mt-6">
          <v-col cols="12">
            <v-card>
              <v-card-title class="text-h5 d-flex justify-space-between align-center">
                <span>
                  <v-icon start color="success">mdi-account-plus</v-icon>
                  参会体验
                </span>
                <v-btn icon @click.stop="refreshJoinableMeetings">
                  <v-icon>mdi-refresh</v-icon>
                </v-btn>
              </v-card-title>
              <v-card-text @click.stop="refreshJoinableMeetings">
                <v-row>
                  <v-col cols="12" md="6">
                    <v-select v-model="joinMeetingId" :items="joinableMeetings" item-title="label" item-value="id"
                      label="选择会议" @update:model-value="showMeetingPreview"></v-select>
                  </v-col>
                  <v-col cols="12" md="3" class="d-flex align-center">
                    <v-btn color="success" @click="handleJoinMeeting" :loading="joinLoading" block>
                      <v-icon start>mdi-account-plus</v-icon>
                      一键参会
                    </v-btn>
                  </v-col>
                </v-row>
                <v-row v-if="meetingPreview">
                  <v-col cols="12">
                    <v-card outlined>
                      <v-card-title>会议信息预览</v-card-title>
                      <v-card-text>
                        <div>主题：{{ meetingPreview.topic }}</div>
                        <div>时间：{{ meetingPreview.time }}</div>
                        <div>会议室：{{ meetingPreview.roomName }}</div>
                      </v-card-text>
                    </v-card>
                  </v-col>
                </v-row>
              </v-card-text>
            </v-card>
          </v-col>
        </v-row>
        <!-- 会议提醒 -->
        <v-row class="mt-6" v-if="notifications.length">
          <v-col cols="12">
            <v-alert type="info" border="left" prominent>
              <div v-for="(item, idx) in notifications" :key="idx">
                会议提醒：{{ item.topic }}，时间：{{ item.time || '未知' }}
              </div>
            </v-alert>
          </v-col>
        </v-row>

        <!-- 已报名参加的会议 -->
        <v-row class="mt-6" v-if="joinedMeetings.length">
          <v-col cols="12">
            <v-card>
              <v-card-title>
                <v-icon start color="primary">mdi-account-group</v-icon>
                已报名参加的会议
              </v-card-title>
              <v-card-text>
                <v-list>
                  <v-list-item v-for="meeting in joinedMeetings" :key="meeting.id">
                    <v-list-item-content>
                      <v-list-item-title>{{ meeting.topic }}</v-list-item-title>
                      <v-list-item-subtitle>
                        时间：{{ meeting.time || '未知' }}，会议室：{{ meeting.roomName || '未知' }}
                      </v-list-item-subtitle>
                    </v-list-item-content>
                  </v-list-item>
                </v-list>
              </v-card-text>
            </v-card>
          </v-col>
        </v-row>

        <!-- 统计信息 -->
        <v-row class="mt-6">
          <v-col v-for="stat in statistics" :key="stat.title" cols="12" md="3">
            <v-card>
              <v-card-text class="text-center">
                <v-icon size="48" :color="stat.color">{{ stat.icon }}</v-icon>
                <div class="text-h4 mt-2">{{ stat.value }}</div>
                <div class="text-body-2">{{ stat.title }}</div>
              </v-card-text>
            </v-card>
          </v-col>
        </v-row>
      </v-container>
    </v-main>

    <!-- 成功提示 -->
    <v-snackbar v-model="showSuccess" color="success">
      {{ successMessage }}
      <template v-slot:actions>
        <v-btn color="white" text @click="showSuccess = false">
          关闭
        </v-btn>
      </template>
    </v-snackbar>

    <!-- 错误提示 -->
    <v-snackbar v-model="showError" color="error">
      {{ errorMessage }}
      <template v-slot:actions>
        <v-btn color="white" text @click="showError = false">
          关闭
        </v-btn>
      </template>
    </v-snackbar>

    <!-- 个人信息对话框 -->
    <v-dialog v-model="showUserInfo" max-width="500">
      <v-card>
        <v-card-title class="text-h5 d-flex align-center">
          <v-icon start color="primary">mdi-account-circle</v-icon>
          个人信息
        </v-card-title>
        <v-card-text>
          <v-row>
            <v-col cols="12">
              <v-text-field v-model="userInfo.email" label="邮箱" readonly outlined></v-text-field>
            </v-col>
            <v-col cols="12">
              <v-text-field v-model="userInfo.username" label="用户名" readonly outlined></v-text-field>
            </v-col>
            <v-col cols="12">
              <v-text-field v-model="userInfo.loginTime" label="登录时间" readonly outlined></v-text-field>
            </v-col>
            <v-col cols="12">
              <v-text-field v-model="userInfo.sessionId" label="会话ID" readonly outlined></v-text-field>
            </v-col>
          </v-row>
        </v-card-text>
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn color="primary" @click="showUserInfo = false">
            关闭
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </v-app>
</template>

<script>
import api from '../services/api.js'

export default {
  name: 'HomePage',
  data() {
    return {
      menuItems: [
        { title: '预约会议室', path: '/booking', icon: 'mdi-calendar-plus' },
        { title: '我的预约', path: '/management', icon: 'mdi-calendar-multiple' },
        { title: '会议室状态', path: '/status', icon: 'mdi-view-dashboard' },
        { title: '账户充值', path: '/recharge', icon: 'mdi-credit-card' }
      ],
      featureCards: [
        {
          title: '预约会议室',
          description: '快速预约会议室，支持时间选择和会议室筛选',
          icon: 'mdi-calendar-plus',
          color: 'primary',
          path: '/booking'
        },
        {
          title: '管理预约',
          description: '查看和管理您的所有预约记录',
          icon: 'mdi-calendar-multiple',
          color: 'success',
          path: '/management'
        },
        {
          title: '会议室状态',
          description: '实时查看所有会议室的占用情况',
          icon: 'mdi-view-dashboard',
          color: 'info',
          path: '/status'
        },
        {
          title: '账户充值',
          description: '安全便捷的支付宝充值服务',
          icon: 'mdi-credit-card',
          color: 'warning',
          path: '/recharge'
        }
      ],
      quickBooking: {
        roomId: null,
        date: '',
        startHour: '',
        endHour: '',
        topic: '',
        loading: false
      },
      availableRooms: [
        { id: 1, name: '会议室A' },
        { id: 2, name: '会议室B' },
        { id: 3, name: '会议室C' },
        { id: 4, name: '会议室D' }
      ],
      timeSlots: [
        { title: '09:00', value: 9 },
        { title: '10:00', value: 10 },
        { title: '11:00', value: 11 },
        { title: '14:00', value: 14 },
        { title: '15:00', value: 15 },
        { title: '16:00', value: 16 }
      ],
      totalMeetings: 0,
      meetingsToday: 0,
      statistics: [
        { title: '总预约数', value: '156', icon: 'mdi-calendar-check', color: 'primary' },
        { title: '今日预约', value: 8, icon: 'mdi-calendar-today', color: 'success' },
        { title: '可用会议室', value: '4', icon: 'mdi-office-building', color: 'info' },
        { title: '预约成功率', value: '95%', icon: 'mdi-chart-line', color: 'warning' }
      ],
      showSuccess: false,
      showError: false,
      successMessage: '',
      errorMessage: '',
      joinMeetingId: null,
      joinableMeetings: [],
      meetingPreview: null,
      joinLoading: false,
      showUserInfo: false,
      userInfo: {
        email: '',
        username: '',
        loginTime: '',
        sessionId: ''
      },
      notifications: [],
      joinedMeetings: [],

    }
  },
  methods: {
    refreshQuickBooking() {
      this.fetchAvailableRooms();
      this.quickBooking.date = '';
      this.quickBooking.startHour = '';
      this.quickBooking.endHour = '';
      this.quickBooking.topic = '';
    },
    refreshJoinableMeetings() {
      this.fetchJoinableMeetings();
      this.meetingPreview = null;
    },
    showMeetingPreview(id) {
      console.log('选择会议ID:', id); // 添加调试日志
      this.meetingPreview = this.joinableMeetings.find(m => m.id === id) || null;
      console.log('会议预览数据:', this.meetingPreview); // 添加调试日志
    },
    async quickBook() {
      if (!this.quickBooking.topic) {
        this.$toast.error('会议主题必填');
        return;
      }
      if (!this.quickBooking.roomId || !this.quickBooking.date) {
        this.showErrorMessage('请选择会议室和日期')
        return
      }

      try {
        this.quickBooking.loading = true

        const startTime = `${this.quickBooking.date}T${this.quickBooking.startHour.toString().padStart(2, '0')}:00:00`
        const endTime = `${this.quickBooking.date}T${this.quickBooking.endHour.toString().padStart(2, '0')}:00:00`

        await api.bookRoom(
          this.quickBooking.roomId,
          startTime,
          endTime,
          this.quickBooking.topic
        )

        this.showSuccessMessage('快速预约成功！')
        this.resetQuickBooking()
      } catch (error) {
        console.error('快速预约失败:', error)
        this.showErrorMessage('快速预约失败，请稍后重试')
      } finally {
        this.quickBooking.loading = false
      }
    },
    resetQuickBooking() {
      this.quickBooking.roomId = null
      this.quickBooking.date = ''
      this.quickBooking.startHour = ''
      this.quickBooking.endHour = ''
      this.quickBooking.topic = ''
    },
    async logout() {
      try {
        await api.logoutUser()
        this.$router.push('/login')
      } catch (error) {
        console.error('退出失败:', error)
        this.showErrorMessage('退出失败，请稍后重试')
      }
    },
    showSuccessMessage(message) {
      this.successMessage = message
      this.showSuccess = true
    },
    showErrorMessage(message) {
      this.errorMessage = message
      this.showError = true
    },
    async handleJoinMeeting() {
      if (!this.joinMeetingId) {
        this.showErrorMessage('请选择会议')
        return
      }
      try {
        this.joinLoading = true
        const res = await api.joinMeeting(this.joinMeetingId)
        this.showSuccessMessage(res.data || '参会成功')
        this.joinMeetingId = null
      } catch (e) {
        // 适配后端统一异常格式
        const msg = e.response?.data?.message || e.response?.data || '参会失败'
        this.showErrorMessage(msg)
      } finally {
        this.joinLoading = false
      }
    },
    async fetchAvailableRooms() {
      try {
        const res = await api.getAllRooms();
        // 假设返回 [{id, roomName}]，适配item-title
        this.availableRooms = (res.data || []).map(r => ({ id: r.id, name: r.roomName }));
      } catch (e) {
        this.showErrorMessage('获取会议室列表失败');
      }
    },
    async fetchJoinableMeetings() {
      try {
        const res = await api.getJoinableMeetings();
        console.log('原始会议数据:', res.data); // 添加调试日志

        // 后端返回的字段是英文：{id, topic, time, roomName}
        this.joinableMeetings = (res.data || []).map(m => {
          console.log('处理单个会议数据:', m); // 添加调试日志
          return {
            ...m,
            label: `#${m.id} ${m.topic}（${m.time || '时间未知'}）`
          };
        });

        console.log('处理后的会议数据:', this.joinableMeetings); // 添加调试日志
      } catch (e) {
        console.error('获取可参会会议失败:', e); // 添加错误日志
        this.showErrorMessage('获取可参会会议失败');
      }
    },

    async checkLoginStatus() {
      try {
        const res = await api.checkLogin();
        if (res.data && res.data.loggedIn) {
          this.showSuccessMessage('登录状态正常');
          // 获取用户信息
          await this.fetchUserInfo();
        } else {
          this.showErrorMessage('登录状态异常，请重新登录');
          setTimeout(() => {
            this.$router.push('/login');
          }, 2000);
        }
      } catch (error) {
        console.error('验证登录状态失败:', error);
        this.showErrorMessage('无法验证登录状态，请重新登录');
        setTimeout(() => {
          this.$router.push('/login');
        }, 2000);
      }
    },

    async fetchUserInfo() {
      try {
        const res = await api.getUserInfo();
        if (res.data) {
          this.userInfo = {
            email: res.data.email || '',
            username: res.data.username || '',
            loginTime: res.data.loginTime || '',
            sessionId: res.data.sessionId || ''
          };
        }
      } catch (error) {
        console.error('获取用户信息失败:', error);
        this.showErrorMessage('获取用户信息失败');
      }
    },
    async fetchNotifications() {
      try {
        const res = await api.getNotifications();
        this.notifications = res.data || [];
      } catch (e) {
        this.showErrorMessage('获取会议提醒失败');
      }
    },
    async fetchJoinedMeetings() {
      try {
        const res = await api.get('/api/bookings/joined');
        this.joinedMeetings = res.data || [];
      } catch (e) {
        this.showErrorMessage('获取已报名会议失败');
      }
    },

  },
  mounted() {
    // 设置默认日期为今天
    this.quickBooking.date = new Date().toISOString().split('T')[0]

    api.get('/api/bookings/config').then(res => {
      this.totalMeetings = res.data.totalMeetings;
      this.statistics[0].value = this.totalMeetings;
      this.meetingsToday = res.data.meetingsToday;
      this.statistics[1].value = this.meetingsToday;
    })
    // 页面加载时验证登录状态
    this.checkLoginStatus()
      ;
    this.fetchNotifications();
    this.fetchJoinedMeetings();
  }
}
</script>

<style scoped>
.h-100 {
  height: 100%;
}

.flex-grow-1 {
  flex-grow: 1;
}
</style>